package com.zzq.controller;

import com.zzq.pojo.Result;
import com.zzq.pojo.Tenderer;
import com.zzq.service.TendererService;
import jakarta.validation.constraints.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/tenderer")
@Validated
public class TendererController {
    @Autowired
    private TendererService tendererService;

    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^[a-zA-Z0-9_]{3,20}$") String username, @Pattern(regexp = "^[a-zA-Z0-9_]{6,20}$") String password, String companyName, String name,String phone, String address) {
        Tenderer tenderer=tendererService.findByTendererName(username);
        if(tenderer==null){
            tendererService.register(username,password,companyName,name,phone,address);
            return Result.success();
        }else {
            return Result.error("用户名已占用");
        }
    }
    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^[a-zA-Z0-9_]{3,20}$") String username, @Pattern(regexp = "^[a-zA-Z0-9_]{6,20}$") String password){
        Tenderer tenderer=tendererService.findByTendererName(username);
        if(tenderer!=null){
            if(tenderer.getPassword().equals(password)){
                return Result.success();
            }else {
                return Result.error("密码错误");
            }
        }else{
            return Result.error("用户名错误");
        }
    }

    @GetMapping("/AllTenderer")
    public Result<List<Tenderer>> AllTenderer(){
        return Result.success(tendererService.list());
    }

    @PutMapping("/deleteTenderer")
    public Result deleteTenderer(int id){
        tendererService.deleteTenderer(id);
        return Result.success();
    }

    @PutMapping("/enit")
    public Result enitTenderer(@RequestBody Tenderer tenderer){
        tendererService.enitTenderer(tenderer);
        return Result.success();
    }

    @GetMapping("/user")
    public Result<Tenderer> user(String username){
        return Result.success(tendererService.findByTendererName(username));
    }
}
